package cn.gov.sdcj.accountancy.rule

import cn.gov.sdcj.accountancy.entity.Entry
import cn.gov.sdcj.accountancy.entity.Item
import cn.gov.sdcj.accountancy.entity.Voucher

/**
 * <p>Description: 根据规则模板构造会计凭证
 * </p>
 *
 * Created by laijie on 2015/3/27.
 */
class RuleBuilder extends BuilderSupport {
    public static final String ENTITY_PACKAGE_NAME = "cn.gov.sdcj.accountancy.entity"
    private final Map ZH2EN_NAME = ['借': { new Entry(dc: 1) }, '贷': { new Entry(dc: 0) }
                                    , 'debit': { new Entry(dc: 1) }, 'credit': { new Entry(dc: 0) }
                                    , '凭证': { new Voucher() }, '凭证字': 'groupName'
                                    , '制单人': 'preparerName', '附件数': 'attachments', '业务日期': 'inputDate'
                                    , '年': 'year', '期间': 'period'
                                    , '科目编码': 'accountNum', '科目名称': 'accountName'
                                    , '金额'  : 'amount', '借贷方向': 'dc', '摘要': 'exp'
                                    , '核算': 'item'
                                    , '单位': { new Item(className: '单位') }
                                    , '项目': { new Item(className: '项目') }
                                    , '核算类别': 'className', '核算编码': 'num', '核算名称': 'name'
                                    , '关联记录': 'relation', '表名': 'className', '类名': 'className', '标识号': 'id'
    ]
    private final Map ZH2EN_VALUE = ['借': 1, '贷': 0,]

    @Override
    protected void setParent(Object parent, Object child) {
        parent.add(child)
    }

    @Override
    protected Object createNode(Object name) {
        def vo
        if (ZH2EN_NAME.containsKey(name) && ZH2EN_NAME[name] in Closure) {
            Closure closure = ZH2EN_NAME[name] as Closure
            vo = closure()
        } else {
            if (ZH2EN_NAME.containsKey(name)) {
                name = ZH2EN_NAME[name];
            }
            Class c = Class.forName(ENTITY_PACKAGE_NAME + ".${name[0].toUpperCase()}${name[1..-1]}")
            vo = c.newInstance()
        }
        return vo
    }

    @Override
    protected Object createNode(Object name, Object value) {
        return ["${ZH2EN_NAME[name] ?: name}": ZH2EN_VALUE[value] ?: value]
    }

    @Override
    protected Object createNode(Object name, Map attributes) {
        def vo = createNode(name)
        vo.add(attributes)
        return vo
    }

    @Override
    protected Object createNode(Object name, Map attributes, Object value) {
        def vo = createNode(name, value)
        return vo
    }

    @Override
    protected void nodeCompleted(Object parent, Object node) {
        super.nodeCompleted(parent, node)
    }
}
